package com.jc.order.service.impl;

import com.jc.order.constant.DataStatusEnum;
import com.jc.order.domain.EciCustomerQuotaApproved;
import com.jc.order.dto.EciCustomerQuotaApplyDTO;
import com.jc.order.dto.EciCustomerQuotaApprovedDTO;
import com.jc.order.mapper.EciCustomerQuotaApprovedMapper;
import com.jc.order.service.EciCustomerQuotaApplyService;
import com.jc.order.service.EciCustomerQuotaApprovedService;
import com.jc.order.util.DTOCompareUtil;
import com.jc.order.util.DTOCompareUtil.FieldChange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EciCustomerQuotaApprovedServiceImpl implements EciCustomerQuotaApprovedService {

    private static final int MAX_BATCH_SIZE = 500; // 批量操作最大尺寸

    @Resource
    private EciCustomerQuotaApprovedMapper eciCustomerQuotaApprovedMapper;

    @Autowired
    private EciCustomerQuotaApplyService customerQuotaApplyService;

    @Override
    public EciCustomerQuotaApprovedDTO selectByCorpSerialNo(String corpSerialNo, Long tenantId) {
        Example example = new Example(EciCustomerQuotaApproved.class);
        example.createCriteria()
                .andEqualTo("tenantId", tenantId)
                .andEqualTo("corpSerialNo", corpSerialNo);

        EciCustomerQuotaApproved entity = eciCustomerQuotaApprovedMapper.selectOneByExample(example);
        return entity != null ? toDTO(entity) : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EciCustomerQuotaApprovedDTO saveCustomerQuotaApproved(EciCustomerQuotaApprovedDTO dto) {
        EciCustomerQuotaApprovedDTO old = this.selectByCorpSerialNo(dto.getCorpSerialNo(), dto.getTenantId());

        if (old == null) {
            // 新增
            EciCustomerQuotaApproved entity = toEntity(dto);
            eciCustomerQuotaApprovedMapper.insert(entity);
            dto.setId(entity.getId());
            log.debug("新增批复记录: corpSerialNo={}", dto.getCorpSerialNo());
        } else {
            // 更新
            dto.setId(old.getId());
            dto.setCreateTime(old.getCreateTime()); // 保留创建时间
            dto.setCreateUser(old.getCreateUser()); // 保留创建用户

            EciCustomerQuotaApproved entity = toEntity(dto);
            Example example = new Example(EciCustomerQuotaApproved.class);
            example.createCriteria()
                    .andEqualTo("tenantId", dto.getTenantId())
                    .andEqualTo("corpSerialNo", dto.getCorpSerialNo());

            eciCustomerQuotaApprovedMapper.updateByExampleSelective(entity, example);

            // 记录变更
            List<FieldChange> changes = DTOCompareUtil.compareObjectChanges(old, dto);
            if (!changes.isEmpty()) {
                log.info("批复记录变更: corpSerialNo={}, 变更字段数={}", dto.getCorpSerialNo(), changes.size());
                changes.forEach(change ->
                        log.debug("字段变更: {}: {} -> {}",
                                change.getFieldName(), change.getOldValue(), change.getNewValue()));
            }
        }
        return dto;
    }

    @Override
    public List<EciCustomerQuotaApprovedDTO> selectByCorpSerialNos(List<String> corpSerialNoList, Long tenantId) {
        if (CollectionUtils.isEmpty(corpSerialNoList)) {
            return Collections.emptyList();
        }

        // 限制批量查询大小
        if (corpSerialNoList.size() > MAX_BATCH_SIZE) {
            log.warn("批量查询数量过大: {} > {}", corpSerialNoList.size(), MAX_BATCH_SIZE);
            corpSerialNoList = corpSerialNoList.subList(0, MAX_BATCH_SIZE);
        }

        Example example = new Example(EciCustomerQuotaApproved.class);
        example.createCriteria()
                .andEqualTo("tenantId", tenantId)
                .andIn("corpSerialNo", corpSerialNoList);

        return toDTOs(eciCustomerQuotaApprovedMapper.selectByExample(example));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean importApproval(List<EciCustomerQuotaApprovedDTO> importList) {
        if (CollectionUtils.isEmpty(importList)) {
            log.warn("导入批复数据为空");
            return false;
        }

        // 提取公司名称用于批量查询
        List<String> riskCompNames = importList.stream()
                .map(EciCustomerQuotaApprovedDTO::getRiskCompName)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询申请记录
        Map<String, EciCustomerQuotaApplyDTO> applyMap = customerQuotaApplyService.getByCompNames(riskCompNames);

        // 准备批量更新和插入的数据
        List<EciCustomerQuotaApplyDTO> updates = new ArrayList<>();
        List<EciCustomerQuotaApproved> entities = new ArrayList<>();

        for (EciCustomerQuotaApprovedDTO dto : importList) {
            // 设置默认流水号
            dto.setCorpSerialNo(dto.getQuotaNo());

            // 查找匹配的申请记录
            EciCustomerQuotaApplyDTO applyDTO = applyMap.get(dto.getRiskCompName());
            if (applyDTO != null) {
                // 更新申请状态
                applyDTO.setDataStatus(DataStatusEnum.DATA_STATUS_PASS.getCode());
                applyDTO.setUpdateTime(new Date());
                applyDTO.setUpdateUser("SYS");
                updates.add(applyDTO);

                // 设置批复信息
                dto.setTenantId(applyDTO.getTenantId());
                dto.setCorpSerialNo(applyDTO.getCorpSerialNo());
            }

            // 转换为实体
            entities.add(toEntity(dto));
        }

        // 批量更新申请记录
        if (!CollectionUtils.isEmpty(updates)) {
            customerQuotaApplyService.batchUpdate(updates);
        }

        // 批量插入批复记录
        if (!CollectionUtils.isEmpty(entities)) {
            eciCustomerQuotaApprovedMapper.insertList(entities);
        }

        log.info("成功导入批复数据: {} 条", importList.size());
        return true;
    }

    @Override
    public List<EciCustomerQuotaApprovedDTO> selectByQuotaNoList(List<String> quotaNoList) {
        if (CollectionUtils.isEmpty(quotaNoList)) {
            return Collections.emptyList();
        }

        // 限制批量查询大小
        if (quotaNoList.size() > MAX_BATCH_SIZE) {
            log.warn("限额号批量查询数量过大: {} > {}", quotaNoList.size(), MAX_BATCH_SIZE);
            quotaNoList = quotaNoList.subList(0, MAX_BATCH_SIZE);
        }

        Example example = new Example(EciCustomerQuotaApproved.class);
        example.createCriteria().andIn("quotaNo", quotaNoList);

        return toDTOs(eciCustomerQuotaApprovedMapper.selectByExample(example));
    }

    // ============== 私有工具方法 ==============

    private EciCustomerQuotaApprovedDTO toDTO(EciCustomerQuotaApproved entity) {
        if (entity == null) return null;
        EciCustomerQuotaApprovedDTO dto = new EciCustomerQuotaApprovedDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    private EciCustomerQuotaApproved toEntity(EciCustomerQuotaApprovedDTO dto) {
        EciCustomerQuotaApproved entity = new EciCustomerQuotaApproved();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    private List<EciCustomerQuotaApprovedDTO> toDTOs(List<EciCustomerQuotaApproved> entities) {
        if (CollectionUtils.isEmpty(entities)) {
            return Collections.emptyList();
        }
        return entities.stream()
                .map(this::toDTO)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}